package net.lz1998.pbbot.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.io.File;
import java.util.stream.IntStream;

public class MeiLvPipeline implements Pipeline{

	private static final ObjectMapper MAPPER = new ObjectMapper();

	@Override
	public void process(ResultItems resultItems, Task task) {
		System.out.println(resultItems);
		String title = resultItems.get("title").toString();
		title=title.replaceAll("\\[","").replaceAll("\\]","");
		String img = resultItems.get("img").toString();
		img=img.replaceAll("\\[","").replaceAll("\\]","");

		String[] titles = title.split(",");
		String[] imgs = img.split(",");
		for (int i = 0; i <titles.length ; i++) {
			try {
				this.downloadFile(imgs[i].trim(),imgs[i].trim(), new File( "E:\\gif\\" + titles[i].trim()+"\\"+ RandomStringUtils.randomNumeric(6) + ".gif"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 下载文件
	 *
	 * @param url 文件url
	 * @param dest 目标目录
	 * @throws Exception
	 */
	public void downloadFile(String imageUrl,String url, File dest) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response =
				HttpClientBuilder.create().build().execute(httpGet);
		try {
			FileUtils.writeByteArrayToFile(dest,
					IOUtils.toByteArray(response.getEntity().getContent()));
			System.out.println("下载完成:"+ url);
		} finally {
			response.close();
		}
	}
}

